package com.shengdou.as.slopsapptest.utils;

import java.util.ArrayList;

/**
 * Created by AS on 2016/11/24.
 * 集合拆分
 */

public class ArrayListSplit {
    /**
     * 拆分集合
     *
     * @param <T>
     * @param resList 要拆分的集合
     * @param count   每个集合的元素个数
     * @return 返回拆分后的各个集合
     */
    public static <T> ArrayList<ArrayList<T>> split(ArrayList<T> resList, int count) {

        if (resList == null || count < 1)
            return null;
        ArrayList<ArrayList<T>> ret = new ArrayList<ArrayList<T>>();
        int size = resList.size();
        if (size <= count) { //数据量不足count指定的大小
            ret.add(resList);
        } else {
            int pre = size / count;
            int last = size % count;
            //前面pre个集合，每个大小都是count个元素
            for (int i = 0; i < pre; i++) {
                ArrayList<T> itemList = new ArrayList<T>();
                for (int j = 0; j < count; j++) {
                    itemList.add(resList.get(i * count + j));
                }
                ret.add(itemList);
            }
            //last的进行处理
            if (last > 0) {
                ArrayList<T> itemList = new ArrayList<T>();
                for (int i = 0; i < last; i++) {
                    itemList.add(resList.get(pre * count + i));
                }
                ret.add(itemList);
            }
        }
        return ret;

    }
}
